package com.lagou.lesson2.service.impl;

import com.lagou.lesson2.core.annotation.Autowired;
import com.lagou.lesson2.core.annotation.Service;
import com.lagou.lesson2.core.annotation.Transactional;
import com.lagou.lesson2.dao.AccountDao;
import com.lagou.lesson2.model.Account;
import com.lagou.lesson2.service.TransferService;
import com.lagou.lesson2.utils.TransactionManager;

@Service("TransferService")
public class TransferServiceImpl implements TransferService {
    @Autowired("AccountDao")
    private AccountDao accountDao;

    static {
        System.out.println("TransferServiceImpl 静态初始化块...");
    }

    @Transactional
    @Override
    public void transfer(String fromCardNo, String toCardNo, Integer money) throws Exception {
        System.out.println("执行转账业务逻辑");
        System.out.printf("accountDao=" + accountDao);
        Account from = accountDao.queryAccountByCardNo(fromCardNo);
        Account to = accountDao.queryAccountByCardNo(toCardNo);

        from.setMoney(from.getMoney()-money);
        to.setMoney(to.getMoney()+money);
        System.out.println("from:" + from.getName() + ", to:" + to.getName());
        System.out.println("amount:" + from.getMoney() + ", toAmount:" + to.getMoney());

        accountDao.updateAccountByCardNo(to);
        if(from.getMoney() < 0) {
            throw new RuntimeException("账户余额不足");
        }
        //int c = 1/0;
        accountDao.updateAccountByCardNo(from);
    }
}
